﻿using System;
using System.Data;
using System.Collections;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Script.Serialization;
using System.Xml;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
/// CWebBase의 요약 설명입니다.
/// </summary>
public class CWebBase : System.Web.UI.Page
{
    // 사용자 정보를 담는 구조체의 인스턴스 - 각 페이지는 이를 통해 사용자 정보를 가져온다.
    private CUserInfo _userinfo;
    public CUserInfo Userinfo
    {
        get
        {
            GetUserInfo();
            return _userinfo;
        }
    }

    public CWebBase()
    {
        _userinfo = new CUserInfo();
    }

    // 사용자 정보를 구조체에 담는 함수
    protected void GetUserInfo()
    {
        if (Session["_Login_User_ID"] != null)
        {
            _userinfo.UserID = Session["_Login_User_ID"].ToString();
            _userinfo.UserName = Session["_Login_User_NAME"].ToString();
        }
        else
        {
            _userinfo.UserID = "";
            _userinfo.UserName = "";
        }
    }

    // 로그인 되었는지 체크하는 함수
    protected void CheckLogin()
    {
        if (Userinfo.UserID == "")
            ErrorGo("로그인 하세요.", "/analyze_new/admin/login.aspx?redirecturl=" + Server.UrlEncode(Request.Url.AbsoluteUri.ToString()));
    }

    // 로그인 되었는지 체크하는 함수 - 팝업창 용도
    protected void CheckLoginPop()
    {
        if (Userinfo.UserID == "")
        {
            Response.Write("<script>alert('로그인 해야 사용할 수 있는 기능입니다.');window.close();</script>");
            Response.End();
        }
    }

    // 로그인 되었는지 체크하는 함수 - Helper 용도
    protected void CheckLoginHelper()
    {
        if (Userinfo.UserID == "")
        {
            string xml = "<ROOT RESULT=\"0\" REASON=\"로그인 해야 사용할 수 있는 기능입니다.\" />";

            Response.ContentType = "text/xml; charset=utf-8";
            Response.Write(xml);
            Response.End();
        }
    }

    // 로그인 되었는지 체크하는 함수 - Helper 용도
    protected void CheckLoginLayer()
    {
        if (Userinfo.UserID == "")
        {
            Response.Write("<script>alert('로그인 해야 사용할 수 있는 기능입니다.');window.parent.close_layer_popup('" + Request.QueryString["layer_no"] + "');</script>");
            Response.End();
        }
    }

    // 쿠키를 세팅할 도메인을 결정하는 함수
    protected string GetCookieDomain()
    {
        string domain = Request.ServerVariables["Server_Name"];

        if (domain.IndexOf(".") == -1)
            return domain;
        else
        {
            domain = domain.Substring(domain.IndexOf(".") + 1).ToLower();
            if (domain == "ac.kr" || domain == "co.kr" || domain == "com")
                return Request.ServerVariables["Server_Name"];
            else
                return domain;
        }
    }

    // XMLHTTP를 통해 전달된 XML을 읽어오는 함수
    protected string GetRequestXML()
    {
        StreamReader reader = new StreamReader(Request.InputStream);
        string result = reader.ReadToEnd();
        reader.Close();
        reader = null;

        return result;
    }

    // 텍스트 파일을 읽는 함수
    protected string ReadTextFile(string pFilePath)
    {
        StreamReader reader = new StreamReader(pFilePath, System.Text.Encoding.Default);
        string result = reader.ReadToEnd();
        reader.Close();

        return result;
    }

    // XML텍스트에 알맞게 인코딩해주는 함수
    protected string MakeXMLString(string pOrgStr)
    {
        if (pOrgStr == null)
            return "";

        return Regex.Replace(pOrgStr.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\0", ""), "[" + (char)1 + "-\b\v\f" + (char)14 + "-" + (char)31 + "]", "_");
    }

    // 태그의 프로퍼티값에 들어가는 형태로 변환하는 함수
    protected string MakePropertyString(string pOrgStr)
    {
        if (pOrgStr == null)
            return "";

        return pOrgStr.Replace("&", "&amp;").Replace("\"", "&quot;");
    }

    // 쿼리문의 검색 문자열에 사용할 수 있게 값을 변경한다.
    protected string MakeSearchField(string pOrgStr)
    {
        if (pOrgStr == null)
            return "";

        return pOrgStr.Replace("'", "''").Replace("[", "[[]").Replace("%", "[%]").Replace("_", "[_]");

    }

    // 쿼리문에 사용할 수 있게 값을 변경한다.
    protected string MakeRightField(string pOrgStr)
    {
        if (pOrgStr == null)
            return "";

        return pOrgStr.Replace("'", "''").Replace("\0", "");
    }

    // MakePropertyString의 단축 함수
    protected string MPS(string pOrgStr)
    {
        return MakePropertyString(pOrgStr);
    }

    // MakeRightField의 단축 함수
    protected string MRF(string pOrgStr)
    {
        return MakeRightField(pOrgStr);
    }

    // 금액에 ',' 표시
    protected string MakePriceFormat(string pOrgStr)
    {
        if (pOrgStr == null)
            return "";

        string price = "";
        string sign = "";

        if (pOrgStr != "" && pOrgStr.Substring(0, 1) == "-")
        {
            sign = "-";
            pOrgStr = pOrgStr.Substring(1);
        }

        while (true)
        {
            if (pOrgStr.Length <= 3)
            {
                price = pOrgStr + price;
                break;
            }
            else
            {
                price = "," + pOrgStr.Substring(pOrgStr.Length - 3) + price;
                pOrgStr = pOrgStr.Substring(0, pOrgStr.Length - 3);
            }
        }

        return sign + price;
    }

    // 
    // 에러 표시 및 URL 이동 관련 함수 모음
    //

    protected void ErrorBack(string pMessage)
    {
        Response.Write("<script>alert(\"" + pMessage + "\");history.go(-1);</script>");
        Response.End();
    }

    protected void ErrorGo(string pMessage, string pUrl)
    {
        Response.Write("<script>alert(\"" + pMessage + "\");window.location.href='" + pUrl + "';</script>");
        Response.End();
    }

    protected void JustGo(string pUrl)
    {
        Response.Write("<script>window.location.href='" + pUrl + "';</script>");
        Response.End();
    }

    protected void ErrorTopGo(string pMessage, string pUrl)
    {
        Response.Write("<script>alert(\"" + pMessage + "\");window.top.location.href='" + pUrl + "';</script>");
        Response.End();
    }

    protected void ErrorClose(string pMessage)
    {
        Response.Write("<script>alert(\"" + pMessage + "\");window.close();</script>");
        Response.End();
    }

    protected void ErrorCloseLayer(string pMessage)
    {
        Response.Write("<script>alert(\"" + pMessage + "\");window.parent.close_layer_popup('" + Request.QueryString["layer_no"] + "');</script>");
        Response.End();
    }

    protected void ErrorCloseRefresh(string pMessage)
    {
        Response.Write("<script>alert(\"" + pMessage + "\");window.opener.location.reload(false);window.close();</script>");
        Response.End();
    }

    protected void JustCloseRefresh()
    {
        Response.Write("<script>window.opener.location.reload(false);window.close();</script>");
        Response.End();
    }

    protected void ErrorCloseOpenerGo(string pMessage, string pUrl)
    {
        Response.Write("<script>alert(\"" + pMessage + "\");window.opener.location.href='" + pUrl + "';window.close();</script>");
        Response.End();
    }

    protected void ErrorCloseOpenerOpenerGo(string pMessage, string pUrl)
    {
        Response.Write("<script>alert(\"" + pMessage + "\");window.opener.location.reload(false);window.opener.opener.location.href='" + pUrl + "';window.close();</script>");
        Response.End();
    }

    // 긴 제목을 자르는 함수
    protected string GetLeftTitle(string pTitle, int pLength)
    {
        if (pTitle == null)
            return "";

        double count = 0;
        string title = "";

        for (int i = 0; i < pTitle.Length; i++)
        {
            if (pTitle.ToCharArray()[i] > 256)
                count += 2;
            else
            {
                if (pTitle.ToCharArray()[i] == '.' || pTitle.ToCharArray()[i] == ',')
                    count += 0.8;
                else
                {
                    if (pTitle.ToCharArray()[i] >= 'A' && pTitle.ToCharArray()[i] <= 'Z')
                        count += 1.5;
                    else
                        count += 1.2;
                }
            }

            if (count > pLength * 2)
                break;

            title += pTitle.Substring(i, 1);
        }

        if (title != pTitle)
            return title + "..";
        else
            return title;
    }

    //
    // 에디터 관련 함수
    //

    protected void insert_editor(string fieldname, string content, string width, string height)
    {
        Response.Write("<div><input type='hidden' id='" + fieldname + "' name='" + fieldname + "' value=\"" + MakePropertyString(content) + "\" style='display:none' /><input type='hidden' id='" + fieldname + "___Config' value='SkinPath=/fckeditor/editor/skins/office2003/' style='display:none' /><iframe id='" + fieldname + "___Frame' src='/fckeditor/editor/fckeditor.html?InstanceName=" + fieldname + "&amp;Toolbar=Default' width='" + width + "' height='" + height + "' frameborder='0' scrolling='no'></iframe></div>");
    }

    //
    // 암호화, 복호화 관련 함수
    //

    protected string EncodeBase64(string pString)
    {
        System.Text.UnicodeEncoding AE = new System.Text.UnicodeEncoding();
        pString = System.Convert.ToBase64String(AE.GetBytes(pString));

        return pString;
    }

    protected string DecodeBase64(string pString)
    {
        pString = System.Text.Encoding.Unicode.GetString(System.Convert.FromBase64String(pString));

        return pString;
    }

    //
    // SQL Injection 처리 관련 함수
    //
    protected string EncodeMd5(string pString)
    {
        pString = FormsAuthentication.HashPasswordForStoringInConfigFile(pString, "MD5").ToLower();

        return pString;
    }

    protected string CheckNumber(string pString)
    {
        if (pString == null)
            return null;

        string number = "0123456789";

        for (int i = 0; i < pString.Length; i++)
        {
            if (number.IndexOf(pString.Substring(i, 1)) == -1)
            {
                Response.Write("잘못된 인자입니다.");
                Response.End();
            }
        }

        return pString;
    }

    protected string CheckFloatNumber(string pString)
    {
        if (pString == null)
            return null;

        string number = "0123456789.-";

        for (int i = 0; i < pString.Length; i++)
        {
            if (number.IndexOf(pString.Substring(i, 1)) == -1)
            {
                Response.Write("잘못된 인자입니다.");
                Response.End();
            }
        }

        return pString;
    }

    protected string CheckDateField(string pString)
    {
        if (pString == null)
            return null;

        string number = "0123456789-";

        for (int i = 0; i < pString.Length; i++)
        {
            if (number.IndexOf(pString.Substring(i, 1).ToLower()) == -1)
            {
                Response.Write("잘못된 인자입니다.");
                Response.End();
            }
        }

        return pString;
    }

    protected string CheckDateTimeField(string pString)
    {
        if (pString == null)
            return null;

        string number = "0123456789-: ";

        for (int i = 0; i < pString.Length; i++)
        {
            if (number.IndexOf(pString.Substring(i, 1).ToLower()) == -1)
            {
                Response.Write("잘못된 인자입니다.");
                Response.End();
            }
        }

        return pString;
    }

    protected string CheckDatabaseField(string pString)
    {
        if (pString == null)
            return null;

        string number = "0123456789_abcdefghijklmnopqrstuvwxyz:";

        for (int i = 0; i < pString.Length; i++)
        {
            if (number.IndexOf(pString.Substring(i, 1).ToLower()) == -1)
            {
                Response.Write("잘못된 인자입니다.");
                Response.End();
            }
        }

        return pString;
    }

    // XML Helper 관련 함수들
    protected string BuildXMLFromStructure(System.Collections.Hashtable map, string tagname)
    {
        StringBuilder xml = new StringBuilder();

        xml.Append("<" + tagname + " TYPE='MAP'>");

        IDictionaryEnumerator en = map.GetEnumerator();

        while (en.MoveNext())
        {
            if (en.Value.GetType().ToString() == "System.Collections.Hashtable")
                xml.Append(BuildXMLFromStructure((Hashtable)en.Value, en.Key.ToString()));
            else if (en.Value.GetType().ToString() == "System.Collections.ArrayList")
                xml.Append(BuildXMLFromStructure((ArrayList)en.Value, en.Key.ToString()));
            else
                xml.Append(BuildXMLFromStructure((string)en.Value, en.Key.ToString()));
        }

        xml.Append("</" + tagname + ">");

        return xml.ToString();
    }

    protected string BuildXMLFromStructure(ArrayList list, string tagname)
    {
        StringBuilder xml = new StringBuilder();
        int start_index = 0;

        string totalcount = "";

        for (int i = 0; i < list.Count; i++)
        {
            if (list[i].GetType().ToString() != "System.Int32")
                break;

            if (totalcount == "")
                totalcount = list[i].ToString();
            else
                totalcount += "," + list[i].ToString();

            start_index++;
        }

        if (totalcount == "")
            xml.Append("<" + tagname + " TYPE='LIST'>");
        else
            xml.Append("<" + tagname + " TYPE='LIST' TOTALCOUNT='" + totalcount + "'>");

        for (int i = start_index; i < list.Count; i++)
        {
            if (list[i].GetType().ToString() == "System.Collections.Hashtable")
                xml.Append(BuildXMLFromStructure((Hashtable)list[i], "LISTITEM"));
            else if (list[i].GetType().ToString() == "System.Collections.ArrayList")
                xml.Append(BuildXMLFromStructure((ArrayList)list[i], "LISTITEM"));
            else
                xml.Append(BuildXMLFromStructure((string)list[i], "LISTITEM"));
        }

        xml.Append("</" + tagname + ">");

        return xml.ToString();
    }

    protected string BuildXMLFromStructure(string value, string tagname)
    {
        return "<" + tagname + ">" + MakeXMLString(value) + "</" + tagname + ">";
    }

    //
    // 기타 함수
    //

    protected string CheckNull(object param)
    {
        if (param == null)
            return "";

        return (string)param;
    }

    protected string CheckNull(object param, string defaultvalue)
    {
        if (param == null)
            return defaultvalue;

        return (string)param;
    }

    protected string SafeSubstring(string value, int length)
    {
        if (value == null)
            return "";

        if (value.Length > length)
            return value.Substring(0, length);
        else
            return value;
    }

    protected int GetArticleNo(string totalcount, string listcount, string page, int index)
    {
        return Convert.ToInt32(totalcount) - ((Convert.ToInt32(page) - 1) * Convert.ToInt32(listcount)) - index;
    }

    protected string GetShortDateFormat(string date)
    {
        if (date == null)
            return "";

        if (date.Trim().Length == 8)
        {
            return date.Substring(0, 4) + "." + date.Substring(4, 2) + "." + date.Substring(6, 2);
        }

        return SafeSubstring(date, 10).Replace("-", ".");
    }

    protected string FormatSize(string size)
    {
        long nsize = Convert.ToInt64(size);

        if (nsize > 1024 * 1024 * 1024)
        {
            size = ((float)Math.Round((double)nsize / 1024 / 1024 / 102.4) / 10).ToString() + "G";
        }
        else if (nsize > 1024 * 1024)
        {
            size = ((float)Math.Round((double)nsize / 1024 / 102.4) / 10).ToString() + "M";
        }
        else if (nsize > 1024)
        {
            size = ((float)Math.Round((double)nsize / 102.4) / 10).ToString() + "K";
        }
        else
            size = "1K";

        return size;
    }

    protected string DecorateTitle(string title, string titlebold, string titlecolor, int maxlength)
    {
        string newtitle = GetLeftTitle(title, maxlength);

        titlebold = titlebold.Trim();
        titlecolor = titlecolor.Trim();

        if (titlebold == "1")
            newtitle = "<b>" + newtitle + "</b>";

        if (titlecolor != "" && titlecolor != "0")
            newtitle = "<font color='" + titlecolor + "'>" + newtitle + "</font>";

        return newtitle;
    }

    protected string RemoveSpecialChars(string title)
    {
        string specialchar = "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?";
        string newtitle = "";

        for (int i = 0; i < title.Length; i++)
        {
            if (specialchar.IndexOf(title.Substring(i, 1)) == -1)
                newtitle += title.Substring(i, 1);
            else
                newtitle += " ";
        }

        newtitle = newtitle.Replace("  ", " ");
        newtitle = newtitle.Replace("  ", " ");
        newtitle = newtitle.Replace("  ", " ");
        newtitle = newtitle.Replace("  ", " ");

        return newtitle;
    }

    protected string GetSettingValue(string name)
    {
        string value = System.Configuration.ConfigurationSettings.AppSettings[name];

        if (value == null)
            return "";
        else
            return value;
    }

    protected string RemoveLink(string contents)
    {
        int pos = 0;

        while (true)
        {
            pos = contents.IndexOf("<a", pos, StringComparison.CurrentCultureIgnoreCase);

            if (pos == -1)
                break;

            int pos2 = contents.IndexOf(">", pos + 1);

            if (pos2 == -2)
                break;

            contents = contents.Substring(0, pos) + contents.Substring(pos2 + 1);
        }

        contents = contents.Replace("</a>", "");
        contents = contents.Replace("</A>", "");

        pos = 0;

        while (true)
        {
            pos = contents.IndexOf("<script", pos, StringComparison.CurrentCultureIgnoreCase);

            if (pos == -1)
                break;

            int pos2 = contents.IndexOf("/script>", pos + 1, StringComparison.CurrentCultureIgnoreCase);

            if (pos2 == -2)
                break;

            contents = contents.Substring(0, pos) + contents.Substring(pos2 + 8);
        }

        contents = contents.Replace("javascript:", "");
        contents = contents.Replace("onclick=", "");
        contents = contents.Replace("onmouseover=", "");
        contents = contents.Replace("onmousedown=", "");
        contents = contents.Replace("onload=", "");

        return contents;
    }

    protected String getJson(object obj){
        String result = "";

        if(obj != null){
            JavaScriptSerializer js = new JavaScriptSerializer();
            result = js.Serialize(obj);
        }

        return result;
    }

    protected Boolean isEmpty(String str)
    {
        Boolean isnull = true;

        if (str != null)
        {
            if (!str.Trim().Equals(""))
            {
                isnull = false;
            }
        }
        return isnull;
    }
}
